<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="属性配置" />
      <el-step title="执行配置" />
      <el-step title="参数配置" />
    </el-steps>
    <el-form v-if="active == 1" ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 80%; margin-left: 50px">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="API名称" prop="apiName">
            <el-input v-model="temp.apiName" placeholder="请选择API名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="API版本" prop="apiVersion">
            <el-input v-model="temp.apiVersion" placeholder="请选择API版本" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="API路径" prop="apiUrl">
            <el-input v-model="temp.apiUrl" placeholder="请选择API路径" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="请求方式" prop="reqMethod">
            <el-select v-model="temp.reqMethod" class="filter-item" placeholder="请选择请求方式">
              <el-option v-for="item in dictList('req_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="返回格式" prop="resType">
            <el-select v-model="temp.resType" class="filter-item" placeholder="请选择返回格式">
              <el-option v-for="item in dictList('res_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="IP黑名单" prop="deny">
            <el-input v-model="temp.deny" type="textarea" placeholder="请输入IP黑名单多个用英文,隔开" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否限流" prop="limitJson.enable">
            <el-radio v-for="item in dictList('is_limit')" :key="'type' + item.label" v-model="temp.limitJson.enable" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-if="temp.limitJson.enable === '1'" label="限流配置">
            每<el-input-number v-model="temp.limitJson.seconds" controls-position="right" :min="1" />秒内限制请求
            <el-input-number v-model="temp.limitJson.times" controls-position="right" :min="1" />次
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio v-for="item in dictList('is_release')" :key="'type' + item.label" v-model="temp.status" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="temp.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form v-if="active == 2" ref="dataForm1" :rules="rules1" :model="temp1" label-position="left" label-width="80px" style="width: 95%; margin-left: 10px">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="配置方式" prop="configType">
            <el-select v-model="temp1.configType" class="filter-item" placeholder="请选择配置方式" :change="configTypeSelectChanged">
              <el-option v-for="item in dictList('config_type')" :key="'type' + item.label" :label="item.label" :value="item.value" @click.native="text" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据源" prop="sourceId">
            <el-select v-model="temp1.sourceId" placeholder="请选择数据源" @change="sourceSelectChanged">
              <el-option v-for="source in sourceOptions" :key="source.id" :label="source.name" :value="source.id" :disabled="source.status === '0'" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-if="temp1.configType === '1'" label="数据库表" prop="tableName">
            <el-select v-model="temp1.tableName" value-key="id" placeholder="请选择数据库表" @change="tableSelectChanged">
              <el-option v-for="item in tableOptions" :key="item.id" :label="item.tableComment ? item.tableComment : item.tableName" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item v-if="temp1.configType === '1'" label="字段列表"></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-if="temp1.configType === '1'">
            <el-table :data="temp1.fieldParams" stripe border :max-height="300" style="width: 100%" v-if="shouldRenderTable" ref="tableall">
              <el-table-column prop="columnPosition" label="序号" width="55" align="center" />
              <el-table-column prop="columnName" label="列名" align="center" show-overflow-tooltip />
              <el-table-column prop="dataType" label="数据类型" align="center" show-overflow-tooltip />
              <el-table-column prop="dataLength" label="数据长度" width="55" align="center" show-overflow-tooltip />
              <el-table-column prop="dataPrecision" label="数据精度" width="55" align="center" show-overflow-tooltip />
              <el-table-column prop="dataScale" label="数据小数位" width="55" align="center" show-overflow-tooltip />
              <el-table-column prop="columnKey" label="是否主键" width="55" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.columnKey === '1'">Y</span>
                  <span v-if="scope.row.columnKey === '0'">N</span>
                </template>
              </el-table-column>
              <el-table-column prop="columnNullable" label="是否允许为空" width="55" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.columnNullable === '1'">Y</span>
                  <span v-if="scope.row.columnNullable === '0'">N</span>
                </template>
              </el-table-column>
              <el-table-column prop="dataDefault" label="列默认值" width="55" align="center" show-overflow-tooltip />
              <el-table-column prop="columnComment" label="列注释" align="center" show-overflow-tooltip />
              <!--              <el-table-column prop="reqable" label="是否作为请求参数" align="center" >-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-checkbox v-model="scope.row.reqable" true-label="1" false-label="0"-->
              <!--                    @change="checked => reqCheckChange(scope.row, checked)" />-->
              <!--                </template>-->
              <!--              </el-table-column>-->

              <el-table-column prop="reqable" label="是否作为请求参数" align="center">
                <template slot="header">
                  <div>
                    <span style="display: block; white-space: pre-line">是否作为请求参数</span>
                    <label>
                      <input type="checkbox" v-model="isAllSelectedReq" @click="selectAllReq" />
                      全选
                    </label>
                  </div>
                </template>
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.reqable" true-label="1" false-label="0" @change="(checked) => reqCheckChange(scope.row, checked)" />
                </template>
              </el-table-column>
              <el-table-column prop="resable" label="是否作为返回参数" align="center">
                <template slot="header">
                  <div>
                    <span style="display: block; white-space: pre-line">是否作为返回参数</span>
                    <label>
                      <input type="checkbox" v-model="isAllSelectedRes" @click="selectAllRes" />
                      全选
                    </label>
                  </div>
                </template>
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.resable" true-label="1" false-label="0" @change="(checked) => resCheckChange(scope.row, checked)" />
                </template>
              </el-table-column>

              <!--              <el-table-column prop="resable" label="是否作为返回参数" align="center" width="50">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-checkbox v-model="scope.row.resable" true-label="1" false-label="0"-->
              <!--                    @change="checked => resCheckChange(scope.row, checked)" />-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="10" v-if="temp1.configType === '2'">
          <el-form-item>
            <el-button size="mini" type="primary" @click="sqlParse">SQL解析</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="temp1.configType === '2'">
          <sql-editor ref="sqleditor" :value="this.temp1.sqlText" style="height: 300px; transform: translate(0px, -10px)" @changeTextarea="changeTextarea($event)" />
        </el-col>
      </el-row>
    </el-form>
    <el-form v-if="active == 3" ref="dataForm2" :model="temp2" label-position="left" label-width="80px" style="width: 95%; margin-left: 25px">
      <el-divider content-position="left">请求参数</el-divider>
      <el-alert title="参数传递可以在params，也可以在body体里。如果参数里有特殊符号，请在body里进行出参。" type="warning" show-icon> </el-alert>
      <el-table :data="temp2.reqParams" stripe border :max-height="300" style="width: 100%; margin: 15px 0">
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paramName" label="参数名称" align="center" show-overflow-tooltip />
        <el-table-column prop="nullable" label="是否允许为空" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.nullable" true-label="1" false-label="0" />
          </template>
        </el-table-column>
        <el-table-column prop="paramComment" label="描述" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.paramComment" placeholder="请输入描述" />
          </template>
        </el-table-column>
        <el-table-column prop="paramType" label="参数类型" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.paramType" placeholder="请选择参数类型">
              <el-option v-for="item in dictList('mysql_data_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="whereType" label="操作符" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.whereType" placeholder="请选择操作符">
              <el-option v-for="item in dictList('sql_where_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="exampleValue" label="示例值" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.exampleValue" placeholder="请输入示例值" />
          </template>
        </el-table-column>
        <el-table-column prop="defaultValue" label="默认值" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" />
          </template>
        </el-table-column>
      </el-table>
      <el-divider content-position="left">返回字段</el-divider>
      <el-table :data="temp2.resParams" stripe border :max-height="300" style="width: 100%; margin: 15px 0">
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fieldName" label="字段名称" align="center" show-overflow-tooltip />
        <el-table-column prop="fieldComment" label="描述" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.fieldComment" placeholder="请输入描述" />
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.dataType" placeholder="请输入数据类型" />
          </template>
        </el-table-column>
        <el-table-column prop="exampleValue" label="示例值" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.exampleValue" placeholder="请输入示例值" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- <div style="height: 50px;"></div> -->
    <div slot="footer" class="dialog-footer">
      <el-button v-if="active > 1" style="margin-top: 12px" @click="handleLastStep">上一步</el-button>
      <el-button v-if="active < 3" style="margin-top: 12px" @click="handleNextStep">下一步</el-button>

      <el-button @click=";(dialogFormVisible = false), (active = 1)">
        {{ $t('table.cancel') }}
      </el-button>
      <el-button v-if="active == 3" type="primary" :loading="loading" @click="dialogStatus === 'create' ? createData() : updateData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {  updateMarketApi, getMarketApi, sqlParse } from '@/api/marketApi/marketApi'
import { fetchsourceList } from '@/api/metadata/source/source'
import { fetchtableList } from '@/api/metadata/table'
import { fetchcolumnList } from '@/api/metadata/column'
import SqlEditor from '@/components/SqlEditor'

export default {
  name: 'MarketApiForm',
  components: { SqlEditor },
  data() {
    return {
      rules: {
        apiName: [{ required: true, message: 'API名称为必填项', trigger: 'blur' }],
        apiVersion: [{ required: true, message: 'API版本为必填项', trigger: 'blur' }],
        apiUrl: [{ required: true, message: 'API路径为必填项', trigger: 'blur' }],
        reqMethod: [{ required: true, message: '请求方式为必填项', trigger: 'blur' }],
        resType: [{ required: true, message: '返回格式为必填项', trigger: 'blur' }],
        status: [{ required: true, message: '状态为必填项', trigger: 'blur' }],
      },
      rules1: {
        sourceId: [{ required: true, message: '数据源为必填项', trigger: 'change' }],
        configType: [{ required: true, message: '配置方式为必填项', trigger: 'change' }],
      },
      temp: {},
      temp1: {},
      temp2: {},
      // 数据源数据字典
      sourceOptions: [],
      active: 1,
      textMap: {
        update: '编辑',
        create: '新建',
      },
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      tableOptions: [],
      isAllSelectedReq: false,
      isAllSelectedRes: false,
      shouldRenderTable: true,
    }
  },
  created() {
    this.getDataSourceList()
  },
  watch: {
    shouldRenderTable(newVal, oldVal) {
      this.$nextTick(() => {
        this.shouldRenderTable = true
      })
    },
  },
  methods: {
    getList() {
      this.$emit('refreshList')
    },
    resetTemp() {
      this.loading = false
      ;(this.temp = {
        id: undefined,
        createBy: undefined,
        dbType: undefined,
        createTime: undefined,
        createDept: undefined,
        updateBy: undefined,
        updateTime: undefined,
        apiName: undefined,
        apiVersion: undefined,
        apiUrl: undefined,
        reqMethod: undefined,
        resType: undefined,
        status: undefined,
        remark: undefined,
        deny: undefined,
        directoryId: '',
        limitJson: {
          enable: '1',
          times: 5,
          seconds: 60,
        },
        executeConfig: {},
        reqParams: [],
        resParams: [],
      }),
        (this.temp1 = {
          sourceId: undefined,
          tableId: undefined,
          tableName: undefined,
          configType: undefined,
          fieldParams: [],
          sqlText: undefined,
        }),
        (this.temp2 = {
          reqParams: [],
          resParams: [],
        })
    },
    handleCreate(directoryId) {
      // alert(directoryId)
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.active = 1
      this.temp.directoryId = directoryId
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    sqlParse() {
      if (!this.temp1.sourceId) {
        this.$message.error('数据源不能为空')
        return
      }
      if (!this.temp1.sqlText) {
        this.$message.error('解析SQL不能为空')
        return
      }
      const data = {}
      data.sourceId = this.temp1.sourceId
      data.sqlText = this.temp1.sqlText
      data.dbType = this.temp1.dbType
      sqlParse(data).then((response) => {
        if (response.data.code === 0) {
          const { data } = response.data
          this.temp2.reqParams = data.reqParams
          this.temp2.resParams = data.resParams
          this.$message.success('解析成功，请进行下一步')
        }
      })
    },
    getDataSourceList() {
      fetchsourceList().then((response) => {
        this.sourceOptions = response.data.data
      })
    },
    tableSelectChanged(item) {
      const data = {}
      data.sourceId = item.id
      data.datasource = item.sourceId
      this.temp1.tableId = item.id
      this.temp1.tableName = item.tableName
      fetchcolumnList(data).then((response) => {
        this.temp1.fieldParams = response.data.data
        this.temp2.reqParams = []
        this.temp2.resParams = []
      })
    },
    selectAllReq(value) {
      if (!this.isAllSelectedReq) {
        this.temp2.reqParams.length = 0
        this.temp1.fieldParams.forEach((row) => {
          row.reqable = '1'
          const json = {}
          json.paramName = row.columnName
          json.paramComment = row.columnComment || undefined
          json.nullable = '0'
          this.temp2.reqParams.push(json)
        })
        this.shouldRenderTable = false
        this.isAllSelectedReq = true
      } else {
        this.temp2.reqParams.length = 0
        this.temp1.fieldParams.forEach((row) => {
          row.reqable = '0'
        })
        this.shouldRenderTable = false

        this.isAllSelectedReq = false
      }
    },
    selectAllRes(value) {
      if (!this.isAllSelectedRes) {
        this.temp2.resParams.length = 0
        this.temp1.fieldParams.forEach((row) => {
          row.resable = '1'
          const json = {}
          json.fieldName = row.columnName
          json.fieldComment = row.columnComment || undefined
          json.dataType = row.dataType || undefined
          this.temp2.resParams.push(json)
        })
        this.shouldRenderTable = false
        this.isAllSelectedRes = true
      } else {
        this.temp2.resParams.length = 0
        this.temp1.fieldParams.forEach((row) => {
          row.resable = '0'
        })
        this.shouldRenderTable = false
        this.isAllSelectedRes = false
      }
    },
    reqCheckChange(row, checked) {
      // alert(row.columnName)
      // console.log(JSON.stringify(row))
      if (checked === '1') {
        const json = {}
        json.paramName = row.columnName
        json.paramComment = row.columnComment || undefined
        json.nullable = '0'
        this.temp2.reqParams.push(json)
        row.reqable = '1'
        this.shouldRenderTable = false
      } else {
        this.shouldRenderTable = false
        this.temp2.reqParams.splice(
          this.temp2.reqParams.findIndex((item) => item.fieldName === row.columnName),
          1
        )
      }
    },
    resCheckChange(row, checked) {
      if (checked === '1') {
        const json = {}
        json.fieldName = row.columnName
        json.fieldComment = row.columnComment || undefined
        json.dataType = row.dataType || undefined
        this.temp2.resParams.push(json)
        row.resable = '1'
      } else {
        this.temp2.resParams.splice(
          this.temp2.resParams.findIndex((item) => item.fieldName === row.columnName),
          1
        )
      }
    },
    /** 步骤条下一步 */
    handleNextStep() {
      if (this.active === 1) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 计算参数
            this.active++
          }
        })
      } else if (this.active === 2) {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.active++
          }
        })
      }
    },
    /** 步骤条上一步 */
    handleLastStep() {
      this.active--
    },
    changeTextarea(val) {
      this.temp1.sqlText = val
    },
    configTypeSelectChanged(val) {
      if (this.temp1.configType === '1' && this.temp1.sourceId && this.tableOptions.length <= 0) {
        const data = {}
        data.sourceId = this.temp1.sourceId
        fetchtableList(data).then((response) => {
          this.tableOptions = response.data.data
          this.temp1.fieldParams = []
        })
      }
    },
    sourceSelectChanged(val) {
      this.temp1.dbType=val.dbType
      if (this.temp1.configType && this.temp1.configType === '1') {
        const data = {}
        data.sourceId = val
        fetchtableList(data).then((response) => {
          this.tableOptions = response.data.data
          this.temp1.fieldParams = []
        })
      }
    },
    createData() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          if (this.temp2.reqParams.length <= 0) {
            this.$message.error('请求参数不能为空')
            return
          }
          if (this.temp2.resParams.length <= 0) {
            this.$message.error('返回字段不能为空')
            return
          }
          this.temp.sourceId = this.temp1.sourceId
          this.temp.executeConfig = this.temp1
          this.temp.reqParams = this.temp2.reqParams
          this.temp.resParams = this.temp2.resParams
          this.loading = true
          updateMarketApi(this.temp)
            .then((response) => {
              this.loading = false
              if (response.data.code === 0) {
                this.dialogFormVisible = false
                this.active = '1'
                this.getList()
                this.$message.success(response.data.msg)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            .catch(() => {
              this.loadingOptions.loading = false
              this.loadingOptions.loadingText = '保存'
              this.loadingOptions.isDisabled = false
            })
        }
      })
    },
    async handleUpdate(id) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.active = 1
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.temp =
        (await getMarketApi(id).then((response) => {
          if (response.data.code === 0) {
            return response.data.data
          }
        })) || {}
      this.temp1 = this.temp.executeConfig
      this.temp1.table = { id: this.temp1.tableId }
      console.log('数据库相关内容=' + JSON.stringify(this.temp.executeConfig))
      console.log('数据库相关内容=' + JSON.stringify(this.temp.reqParams))
      this.temp2.reqParams = this.temp.reqParams
      this.temp2.resParams = this.temp.resParams
      if (this.temp1.configType === '1') {
        this.tableOptions = await fetchtableList({ sourceId: this.temp1.sourceId }).then((response) => {
          if (response.data.code === 0) {
            return response.data.data
          }
        })
      }
    },
    updateData() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          if (this.temp2.reqParams.length <= 0) {
            this.$message.error('请求参数不能为空')
            return
          }
          if (this.temp2.resParams.length <= 0) {
            this.$message.error('返回字段不能为空')
            return
          }
          this.temp.sourceId = this.temp1.sourceId
          this.temp.executeConfig = this.temp1
          this.temp.reqParams = this.temp2.reqParams
          this.temp.resParams = this.temp2.resParams
          this.loading = true
          updateMarketApi(this.temp)
            .then((response) => {
              this.loading = false
              if (response.data.code === 0) {
                this.dialogFormVisible = false
                this.active = '1'
                this.getList()
                this.$message.success(response.data.msg)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            .catch(() => {
              this.loadingOptions.loading = false
              this.loadingOptions.loadingText = '保存'
              this.loadingOptions.isDisabled = false
            })
        }
      })
    },
  },
}
</script>
